import service, { axiosAll, setAuthorization, getQueryObject } from './fetch';
const utils = {
    service,
    axiosAll,
    setAuthorization,
    getQueryObject
}

Array.prototype.combination = function (num) {
    var r = [];
    (function f(t, a, n) {
       if (n == 0) return r.push(t);
       for (var i = 0, l = a.length; i <= l - n; i++) {
           f(t.concat(a[i]), a.slice(i + 1), n - 1);
       }
    })([], this, num);
    return r;
}

Date.prototype.Format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,
        //月份
        "d+": this.getDate(),
        //日
        "h+": this.getHours(),
        //小时
        "m+": this.getMinutes(),
        //分
        "s+": this.getSeconds(),
        //秒
        "q+": Math.floor((this.getMonth() + 3) / 3),
        //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

utils.goToPage = function(pageName) {
    if(process.env.NODE_ENV === "development") {
        window.location.href = location.protocol+"//"+(location.host+'/'+pageName).replace("//", "/");
    } else {
        if(process.env.VUE_APP_MODE != "android") {
            window.location.href = location.protocol+"//"+(location.host+'/'+process.env.VUE_APP_OUTPUT_DIR+'/'+pageName).replace("//", "/");
        } else {
            window.location.href = location.protocol+"//"+(location.host+'/android_asset/'+pageName).replace("//", "/");
        }
    }
}

/**
* 频率控制函数， fn执行次数不超过 1 次/delay
* @param fn{Function}     传入的函数
* @param delay{Number}    时间间隔
* @param options{Object}  如果想忽略开始边界上的调用则传入 {leading:false},
*                         如果想忽略结束边界上的调用则传入 {trailing:false},
* @returns {Function}     返回调用函数
*/

function throttle(fn,delay,options){
    var wait =false;
    options = options||{};
    return function(){
        var that = this,args = arguments;
        if(!wait){
            if(!(options.leading===false)){
                fn.apply(that,args);
            }
            wait = true;
            setTimeout(function(){
                if(!(options.trailing===false)){
                    fn.apply(that,args);
                }
                wait = false;
            },delay);
        }
    }
}
/**
 * 空闲控制函数， fn仅执行一次
 * @param fn{Function}     传入的函数
 * @param delay{Number}    时间间隔
 * @param options{Object}  如果想忽略开始边界上的调用则传入 {leading:false},
 *                         如果想忽略结束边界上的调用则传入 {trailing:false},
 * @returns {Function}     返回调用函数
*/
function debounce(fn,delay,options){
    var timeoutId,leadingExc = false;
    options = options||{};

    return function(){
        var that = this,args = arguments;
        if(!leadingExc&&!(options.leading === false)){
            fn.apply(that,args);
        }
        leadingExc = true;
        if(timeoutId){
            clearTimeout(timeoutId);
        }

        timeoutId = setTimeout(function(){
            if(!(options.trailing===false)){
                fn.apply(that,args);
            }
            leadingExc = false;
        },delay)
    }
}


function wxConfig(jsApiList) {
    return new Promise((resolve, reject) => {
        var promises = [
        ];
        var qs = getQueryObject();
        if(!sessionStorage.getItem("Authorization")) {
            if(qs.code) {
                promises.push(
                    utils.service({
                        url: '/m/user/login',
                        method: 'post',
                        data: {
                            code: qs.code,
                            state: qs.state
                        }
                    })
                )
                sessionStorage.setItem("state", qs.state);
            }
        }
        
        utils.axiosAll(
            promises
        )
        .then((promisesData) => {
            if(!sessionStorage.getItem("Authorization")) {
                if(qs.code) {
                    setAuthorization(promisesData[0]);
                } else {
                    setAuthorization();
                }
            } else {
                setAuthorization(sessionStorage.getItem("Authorization"));
            }
            resolve({status: "ok"});
        })
    })
}


function wechatConfigInit(jsApiList) {
    wx.hideOptionMenu();
    return new Promise((resolve, reject) => {
        utils.service({
            url: '/m/jssdk/get',
            method: 'post',
            data: {
                url: window.location.href.split("#")[0]
            }
        }).then((sdkData) => {
            var timeoutFlag = true;
            wx.config({
                debug: false,
                appId: sdkData.publicAppid,
                timestamp: sdkData.timestamp,
                nonceStr: sdkData.noncestr,
                signature: sdkData.signature,
                jsApiList: jsApiList||[
                    'checkJsApi',
                    'hideOptionMenu',
                    'hideAllNonBaseMenuItem',
                    'onMenuShareAppMessage',
                    'onMenuShareTimeline',
                    'showMenuItems',
                    'getLocation',
                    'openLocation',
                    'openAddress',
                    'chooseWXPay'
                ]
            });

            wx.ready(function() {
                wx.hideOptionMenu();
                wx.hideAllNonBaseMenuItem();
                WeixinJSBridge.invoke("hideToolbar");
                wx.showMenuItems({
                    menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:profile'] // 要显示的菜单项，所有menu项见附录3
                });
                timeoutFlag = false;
                resolve({status: "ok"});
            });

            wx.error(function(err) {
                alert(JSON.stringify(err));
                timeoutFlag = false;
                reject({status: "fail"});
            });
            setTimeout(()=> {
                if(timeoutFlag) {
                    reject({status: "fail"}); 
                }
            }, 2000)
        })
    })
}

function createAuthLink(page) {
    page+="&appid="+sessionStorage.getItem("state");
    return `http://prod-api.fastice-tech.com/m/access?page=/${process.env.VUE_APP_OUTPUT_DIR}/${page}`;
}

function shareHandler(shareOptions) {
    if(shareOptions.type == "timeLine") {
        wx.onMenuShareTimeline({
            title: shareOptions.shareTitle,
            desc: shareOptions.shareDesc,
            link: shareOptions.shareUrl,
            imgUrl: shareOptions.sharePic||"http://hsensor.oss-cn-shanghai.aliyuncs.com/cloud/img/aTcMzkXj_1.png",
            success: function() {
                if(shareOptions.callBack && typeof shareOptions.callBack === "function" ) {
                    shareOptions.callBack();
                }
            }
        });
    } else if(shareOptions.type == "appMessage") {
        // 发送给朋友
        wx.onMenuShareAppMessage({
            title: shareOptions.shareTitle,
            desc: shareOptions.shareDesc,
            link: shareOptions.shareUrl,
            imgUrl: shareOptions.sharePic||"http://hsensor.oss-cn-shanghai.aliyuncs.com/cloud/img/aTcMzkXj_1.png",
            type: '',
            dataUrl: '',
            success: function() {
                if(shareOptions.callBack && typeof shareOptions.callBack === "function" ) {
                    shareOptions.callBack();
                }
            }
        });
    }
}

utils.debounce = debounce;
utils.throttle = throttle;
utils.wxConfig = wxConfig;
utils.createAuthLink = createAuthLink;
utils.shareHandler = shareHandler;

utils.MixinBase = {
    methods: {
        wechatInit: wxConfig,
        wechatConfigInit: wechatConfigInit,
        goPersonCenter() {
            utils.goToPage("person_center.html")
        },
        goToHome() {
            utils.goToPage("index.html")
        }
    }
}

export default utils